#!/bin/sh

format_rwfs()
{
    echo "Formatting persistent volume: "
    cat /run/format-persist

    if ! ubiformat --yes /dev/mtd/rwfs ; then
        return 1
    fi

    if ! ubiattach -p /dev/mtd/rwfs ; then
        return 1
    fi

    if ! ubimkvol /dev/ubi0 -N rwfs -m ; then
        return 1
    fi

    return 0
}

if [ ! -e /dev/mtd/rwfs ]; then
    exit 1
fi

# If "no-persist-fs" is set, only mount as a tmpfs and exit, so that we can
# still create writable file system entries.
if /sbin/fw_printenv -n openbmconce | grep -w -q "no-persist-fs"; then
    echo "Mounting /run/mnt-persist as tmpfs"
    if ! mkdir -p /run/mnt-persist ; then
        exit 1
    fi

    if ! mount -t tmpfs tmpfs /run/mnt-persist ; then
        exit 1
    fi

    exit
fi

if [ ! -e /run/format-persist ]; then
    if ! ubiattach -p /dev/mtd/rwfs > /dev/null ; then
        echo "unformatted-ubi" >> /run/format-persist
    fi

    if ! ubinfo /dev/ubi0 -N rwfs > /dev/null ; then
        # ubi device attached, but volume not exist
        ubidetach -p /dev/mtd/rwfs
        echo "missing-ubi-volume" >> /run/format-persist
    fi
fi

if [ -e /run/format-persist ]; then
    if ! format_rwfs; then
        exit 1
    fi
fi

mkdir -p /run/mnt-persist

if ! mount -t ubifs ubi0:rwfs /run/mnt-persist -o sync,compr=zstd; then
    # mount failed, try formatting
    ubidetach -p /dev/mtd/rwfs
    echo "mount-ubi0-rwfs-fail" > /run/format-persist
    if ! format_rwfs; then
        exit 1
    fi

    # mount again after formatting
    mount -t ubifs ubi0:rwfs /run/mnt-persist -o sync,compr=zstd
fi
